
from info.models import User
#导入flask 的内置的对象
from flask import  request,jsonify,current_app,make_response,session,g
#导入蓝图对象
from . import passport_blue
#导入自定义的状态码
from info.utils.response_code import RET
#导入工具capcha
from info.utils.captcha.captcha import captcha
from info.utils.commons import login_required
import re,random
from info.libs.yuntongxun.sms import CCP
# from info.utils.comments import login_required
#导入redis数据库的实例
from info import redis_store,db
# 生成图片验证码
@passport_blue.route('/imagecode')
def image_code():

    '''

    1 获取uuid,imagecode
    2 判断获取是否成功，如果没有uuid，直接终止程序运行
    3调用capcha扩展包，生成图片验证码，mane，text，image
    4把图片验证码的内容，存入redis数据库，根据uuid作为后缀名
    5把图片返回前端
#mobile   phonecode  password  password2
    获取图片验证码 获取短信验证码 注册 登录 判断是否登录 退出登录

    '''
    image_code = request.args.get('cur')
    if not image_code:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        name, text, image = captcha.generate_captcha()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='生成验证码失败')
    print('图片码：', text)
    try:
        redis_store.setex('imagecode_' + image_code, 300, text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储验证码失败')

    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp


# 验证图片验证码，生成随机码并发送给用户
@passport_blue.route('/smscode', methods=['POST'])
def smscode():
    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')

    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.DATAERR, errmsg='请输入正确手机号')

    try:
        real_image_code = redis_store.get('imagecode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='读取验证信息失败')
    try:
        redis_store.delete('imagecode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)

    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg='验证码错误')

    # 判断用户是否存在
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='读取用户数据失败')
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='用户已注册')

    # 生成随机验证码
    text_code = '%06d' % random.randint(0, 999999)
    print(text_code)

    try:
        redis_store.setex('smscode_' + mobile, 300, text_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储随机码失败')

    try:

        ret = CCP().send_template_sms(mobile, [text_code, 5], 1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='网络异常')

    if ret == 0:
        return jsonify(errno=RET.OK, errmsg='信息发送成功')
    else:
        return jsonify(errno=RET.THIRDERR, errmsg='信息发送失败')


# 获得短信验证码后开始注册
@passport_blue.route('/user', methods=['POST'])
def user():
    mobile = request.json.get('mobile')
    smscode = request.json.get('phonecode')
    password = request.json.get('password')

    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        real_smscode = redis_store.get('smscode_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='读取信息失败')

    if int(smscode) != int(real_smscode):
        return jsonify(errno=RET.DATAERR, errmsg='验证码错误')

    user = User()
    user.mobile = mobile
    user.password = password
    user.name = mobile

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储用户信息失败')

    try:
        redis_store.delete('smscode_' + mobile)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='注册成功')


@passport_blue.route('/session', methods=['GET', 'POST', 'DELETE'])
@login_required
def fnSession():
    if request.method == 'DELETE':
        # redis_store.delete('user_id')
        session.pop('user_id', None)
        return jsonify(errno=RET.OK, errmsg='OK')

    if request.method == 'GET':
        user = g.user
        data = {
            'name': user.name,
            'user_id': user.id
        } if user else  None
        return jsonify(errno=RET.OK, errmsg='OK', data=data)

    if request.method == 'POST':

        mobile = request.json.get('mobile')
        password = request.json.get('password')

        if not all([mobile, password]):
            return jsonify(errno=RET.PARAMERR, errmsg='登陆参数缺失')

        if not re.match(r'1[3456789]\d{9}$', mobile):
            return jsonify(errno=RET.DATAERR, errmsg='请输入正确手机号')

        try:
            user = User.query.filter(User.mobile == mobile).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='读取用户数据失败')

        if not user or not user.check_passowrd(password):
            return jsonify(errno=RET.NODATA, errmsg='用户名或密码输入错误')

        session['user_id'] = user.id
        return jsonify(errno=RET.OK, errmsg="登陆成功")






















